﻿using FinalTestMachine.Manger;
using FinalTestMachine.Motion;
using FinalTestMachine.Motion.Product;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;

namespace FinalTestMachine.View.MES
{
    class FinalTestMesHelper
    {
        public static readonly FinalTestMesHelper Cur = new FinalTestMesHelper();

        public static IConnectDLL.IConnect connect => Connect.ConnectFactory.tcpConnect_MES;

        private FinalTestMesHelper()
        {
            saveRead = new SaveReaddll.SaveReadHeler(() => SavePath, () => this);
            Read();
            connect.RecevieMsgActionEventHander += Cur_getMasterMsgEventHandle;
        }

        public static FinalTestMesHelper CreateInstrance()
        {
            return Cur;
        }

        public static event Action<string, Brush> MesInfoEventHandler;
        public static void Cur_getMasterMsgEventHandle(string GetMesInfo)
        {

            if (GetMesInfo != null)
            {
                LogManger.LogMES.LogW(GetMesInfo);
                string[] tempArray = GetMesInfo.Split(';');
                switch (tempArray[1].Split(':')[1].ToUpper())
                {
                    case "CHECKSN":
                        bl = true;
                        LogManger.LogMES.LogW($"checksn，{tempArray[2].Split(',')[0].Split(':')[1].Split('=')[1]}");
                        if (tempArray[2].Split(',')[0].Split(':')[1].Split('=')[1] == "OK")
                        {
                            IsCheckSnOK = true;
                        }
                        else
                        {
                            IsCheckSnOK = false;
                        }
                        break;
                    case "DATAUP":
                        data = true;
                        if (tempArray[2].Split(',')[0].Split(':')[1].Split('=')[1] == "OK")
                        {
                            IsCheckDataOK = true;
                        }
                        else
                        {
                            IsCheckDataOK = false;
                        }
                        break;
                }
            }
        }

        public string MesInfo { get; set; }

        public Brush Brush { get; set; }

        public string ErrMesInfo { get; set; }

        public static bool IsCheckSnOK { get; set; }

        public static bool IsCheckDataOK { get; set; }

        public static bool bl { get; set; } = false;

        public static bool data { get; set; } = false;



        public const string Mes_Station = "";



        int t_sn = 0;
        int t_data = 0;

        private static void Sleep(int t)
        {
            Thread.Sleep(t);
        }
        readonly object _lock = new object();
        readonly object _lock_data = new object();
        private void SendToMEsSN(string msg)
        {
            lock (_lock)
            {
                t_sn = 0;
                bl = false;
                connect.Send(msg);
            }
        }
        private void SendToMEsData(string msg)
        {
            lock (_lock_data)
            {
                t_data = 0;
                data = false;
                connect.Send(msg);
            }
        }

        [ISaveReaddll.SaveRemark]
        public string TestImage { get; set; } = "";

        [ISaveReaddll.SaveRemark]
        public string ResultImage { get; set; } = "";


        string SavePath => System.IO.Path.Combine(ParamPath_Motion.SelectedDirPath, "CalibrateMesParam.ini");


        SaveReaddll.SaveReadHeler saveRead;

        public void Save()
        {
            saveRead?.Save();
        }

        public void Read()
        {
            saveRead?.Read();
        }




















        /// <summary>
        /// 自动流程检查SN
        /// </summary>
        /// <param name="Sn"></param>
        /// <returns></returns>
        public bool CheckSN(string Sn)
        {
            string msg = $"ff0x02;Command:CheckSn;Station:{Mes_Station};Data:Sn={Sn},Model={WorkItemManagerHelper.LoadedName};#end";
            SendToMEsSN(msg);
            while (!bl)
            {
                t_sn++;
                if (t_sn > 50)
                {
                    t_sn = 0;
                    ErrMesInfo = "MES响应超时";
                    return false;
                }
                Sleep(100);
            }
            if (!IsCheckSnOK)
            {
                ErrMesInfo = "单条码检查失败";
                return false;
            }
            return true;
        }


        public bool DataUp(ProductInfo productinfo)
        {
            string result = "";
            if (productinfo.Site2_Station.Result == TestResult.OK && productinfo.Site3_Station.Result == TestResult.OK && productinfo.Site4_Station.Result == TestResult.OK)
            {
                result = "OK";
            }
            else
            {
                result = "NG";
            }
            productinfo.DataUpInfo = ListMsgToUpdataInfo(productinfo.Site2_Station.StationTestItems, productinfo.Site3_Station.StationTestItems, productinfo.Site4_Station.StationTestItems);
            string msg = $@"ff0x04;Command:DataUp;Station:{Mes_Station};Data:Sn={productinfo.Number},TestResult={result},Model={WorkItemManagerHelper.LoadedName},StartTime={productinfo.MesStartTime},EndTime={productinfo.MesEndTime},TestValue={productinfo.DataUpInfo};TestImage={TestImage}\{productinfo.Number}.{OtherParamHelper.Cur.FinalTestImageFormat.GetValue};ResultImage={ResultImage}\{productinfo.Number}.{OtherParamHelper.Cur.FinalTestImageFormat.GetValue};Enabled=1;#end";
            SendToMEsData(msg);
            while (!data)
            {
                t_data++;
                if (t_data > 50)
                {
                    t_data = 0;
                    ErrMesInfo = "MES响应超时";
                    return false;
                }
                Sleep(100);
            }
            if (!IsCheckDataOK)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将数据格式转换为MES需要的格式（Name@最大值@最小值@Value@Result|）
        /// </summary>
        /// <param name="testItems1"></param>
        /// <param name="testItems2"></param>
        /// <param name="testItems3"></param>
        /// <returns></returns>
        private string ListMsgToUpdataInfo(List<ProductTestStationTestItem> testItems1, List<ProductTestStationTestItem> testItems2, List<ProductTestStationTestItem> testItems3)
        {
            string MesInfo = "";
            if (testItems1.Count != 0)
            {
                foreach (var item in testItems1)
                {
                    if (string.IsNullOrEmpty(MesInfo))
                    {
                        MesInfo = $"{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
                    else
                    {
                        MesInfo = $"|{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
              
                }
            }
            if (testItems2.Count != 0)
            {
                foreach (var item in testItems1)
                {
                    if (string.IsNullOrEmpty(MesInfo))
                    {
                        MesInfo = $"{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
                    else
                    {
                        MesInfo = $"|{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
                }
            }
            if (testItems3.Count != 0)
            {
                foreach (var item in testItems1)
                {
                    if (string.IsNullOrEmpty(MesInfo))
                    {
                        MesInfo = $"{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
                    else
                    {
                        MesInfo = $"|{item.name}@{item.upLimit}@{item.lowLimit}@{item.value}@{item.result}";
                    }
                }
            }
            return MesInfo;

        }





    }
}
